package com.sky.demo.mq.rocketmq.base.producer;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * 异步消息发送
 */
public class AsyncProducer {

    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        producer.setNamesrvAddr("192.168.1.222:9876");
        producer.start();
        for (int i = 0; i < 100; i++) {
            Message msg = new Message("TopicTest" /* Topic */,
                    "TagA" /* Tag */,
                    ("Hello RocketMQ " +
                            i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
            //异步消息通过回调函数处理结果
            producer.send(msg, new SendCallback() {

                /**
                 * 发送成功回调函数
                 * @param sendResult 结果
                 */
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(sendResult);
                }

                /**
                 * 发送失败回调函数
                 * @param throwable 异常
                 */
                @Override
                public void onException(Throwable throwable) {
                    System.out.println(throwable.getMessage());
                }
            });

        }
        producer.shutdown();
    }
}
